<?php


namespace app\api\controller;

use app\admin\model\Thumbs;
use app\common\controller\Api;
use app\admin\model\Playlet\Playlet as PlayletModel;
use app\admin\model\Playlet\PlayletChapter as PlayletChapterModel;
use think\Request;

class PlayletChapter extends Api
{
    protected $noNeedLogin = ['*'];

    /** 章节列表
     * @param Request $request
     */
    public function list(\think\Request $request)
    {
        if (!$request->isPost()) {
            $this->error('ＤＯＮ＇Ｔ　ＧＥＴ');
        }
        $req = $request->post();
        $where = ['status' => 'normal', 'playlet_id' => $req['playlet_id']];

        $res = PlayletChapterModel::where($where)->field('video_image,video_url,title,id,weigh,thumbs,comment')->orderRaw('weigh asc')->paginate($req['every'],false, ['var_page' => 'current']);

        if ( $this->auth->isLogin()) {
            $user = $this->auth->getUserinfo();

            foreach ($res as &$value) {
                //点赞
                $n = Thumbs::where(['userid' => $user['id'], 'thumbsid' => $value['id'], 'class' => 3])->count();
                if ($n) {
                    $value['give'] = 1;
                } else {
                    $value['give'] = 0;
                }

            }
        }
        $this->result('短剧', $res, 200);
    }

    //点赞
    public function thumbs(Request $request)
    {
        if (!$request->isGet()) {
            $this->error('ＭＵＳＴ　ＢＥ　ＧＥＴ');
        }
        $user = $this->auth->getUser();
        $req = $request->get();
        $id = $req['id'];
        $find = Thumbs::where(['userid' => $user['id'], 'thumbsid' => $id, 'class' => 3])->find();
        if ($find) {
            $this->result('您已经点过赞了', '', 100);
        } else {
            $thumbs = new Thumbs();
            $res = $thumbs->save(['userid' => $user['id'], 'thumbsid' => $id, 'class' => 3]);
        }
        $playlet_id = PlayletChapterModel::where(['id' => $id])->value('playlet_id');

        if ($res) {
            $res = PlayletChapterModel::where('id', $id)->setInc('thumbs', 1);
            $res = PlayletModel::where('id', $playlet_id)->setInc('thumbs', 1);

            $res = Task::upload($user->id, 4);
            if ($res) {
                $this->success('ok', '', 200);
            }
        } else {
            $this->error('系统错误或网络错误', '', 100);
        }
    }
}
